<?php

namespace addons\mplogin\library;

use think\Cache;

class Custom
{

    private $conf = [];
    private $redirect_uri = '';

    public function __construct()
    {
        $this->conf = get_addon_config('mplogin');
    }

    private function http_request($url, $method = 'GET', $data = [], $result = 'array')
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        if (strtoupper($method) == 'POST') {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        $output = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        if ($httpCode === 0) {
            exception(curl_error($ch));
        }
        return $result == 'array' ? json_decode($output, true) : $output;
    }

    private function api_access_token($refresh=false)
    {
        $access_token = Cache::get($this->conf['appid']);
        if ($access_token && $refresh==false) {
            return $access_token;
        }
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->conf['appid']}&secret={$this->conf['appsecret']}";
        $data = $this->http_request($url);
        if(isset($data['errcode'])){
            exception(json_encode($data));
        }
        Cache::set($this->conf['appid'], $data['access_token'], 7000);
        return $data['access_token'];
    }

    public function userInfo($openid)
    {
        $access_token = $this->api_access_token();
        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$access_token}&openid={$openid}&lang=zh_CN";
        $data=$this->http_request($url);
        if(isset($data['errcode'])){
            $refresh_num=Cache::has($this->conf['appid']."_refresh")?Cache::get($this->conf['appid']."_refresh"):0;
            if($refresh_num>3){
                Cache::set($this->conf['appid']."_refresh",0);
                exception(json_encode($data));
            }
            $this->api_access_token(true);
            Cache::set($this->conf['appid']."_refresh",++$refresh_num);
           return $this->userInfo($openid);
        }
        return $data;
    }

    public function getCode($state = '')
    {
        !$this->redirect_uri && $this->redirect_uri = request()->server('HTTP_REFERER');
        $redirect_uri = urlencode($this->redirect_uri);
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->conf['appid']}&redirect_uri={$redirect_uri}&response_type=code&scope={$this->conf['scope']}&state={$state}#wechat_redirec";
        header("Location:{$url}");
        exit;
    }

    public function setRedirect_uri($redirect_uri)
    {
        $redirect_uri && $this->redirect_uri = $redirect_uri;
        return $this;
    }

    public function codeToUserInfo()
    {
        $code = request()->param('code');
        if (empty($code)) {
            exception('invalid code');
        }
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$this->conf['appid']}&secret={$this->conf['appsecret']}&code={$code}&grant_type=authorization_code";
        $data = $this->http_request($url);
        return $this->userInfo($data['openid']);
    }


    public function template_notice($data=[])
    {
        $access_token = $this->api_access_token();
        $url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={$access_token}";
        return $this->http_request($url,'POST',json_encode($data,JSON_UNESCAPED_UNICODE));
    }
}